﻿/* Copyright © 2010 Nolics
Nolics.net and NSQLObjects are trademarks of Nolics.

Microsoft Public License (Ms-PL)

This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.

2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.

3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 
 */

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.IO;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using NSQLObjects.VS2010Plugin.Syntax;
using Microsoft.VisualStudio;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Data;

namespace NSQLObjects.DBModelClassifier
{

    [Export(typeof(IViewTaggerProvider))]
    [ContentType("dbmodel")]
    [Order(Before = "default")]
    [TagType(typeof(SmartTag))]
    internal class QuerySmartTaggerProvider : IViewTaggerProvider
    {
        [Import(typeof(ITextStructureNavigatorSelectorService))]
        internal ITextStructureNavigatorSelectorService NavigatorService { get; set; }

        [Import]
        internal ITextBufferFactoryService TextBufferFactoryService { get; set; }

        [Import]
        internal IContentTypeRegistryService RegistryService { get; set; }

        [Import]
        internal ITextEditorFactoryService TextEditorFactory { get; set; }

        [Import]
        internal SVsServiceProvider ServiceProvider { get; set; }

        [Import]
        internal IVsEditorAdaptersFactoryService EditorAdapterFactory { get; set; }

        #region IViewTaggerProvider Members

        public ITagger<T> CreateTagger<T>(ITextView textView, ITextBuffer buffer) where T : ITag {
            if (buffer == null || textView == null) {
                return null;
            }

            return new QuerySmartTagger(buffer, textView, this) as ITagger<T>;
        }

        #endregion
    }

    internal class QuerySmartTag : SmartTag
    {
        public QuerySmartTag(ReadOnlyCollection<SmartTagActionSet> actionSets) :
            base(SmartTagType.Factoid, actionSets) { }

    }

    internal class QuerySmartTagger : ITagger<QuerySmartTag>, IDisposable
    {
        public QuerySmartTagger(ITextBuffer buffer, ITextView view, QuerySmartTaggerProvider provider) {
            this.buffer = buffer;
            this.view = view;
            this.provider = provider;
            view.LayoutChanged += new EventHandler<TextViewLayoutChangedEventArgs>(view_LayoutChanged);
        }

        void view_LayoutChanged(object sender, TextViewLayoutChangedEventArgs e) {
            if (TagsChanged != null)
                TagsChanged(this, new SnapshotSpanEventArgs(new SnapshotSpan(e.NewSnapshot, new Span(0, e.NewSnapshot.Length))));

        }

        private ITextBuffer buffer;
        private ITextView view;
        private QuerySmartTaggerProvider provider;


        #region ITagger<QuerySmartTag> Members

        public IEnumerable<ITagSpan<QuerySmartTag>> GetTags(NormalizedSnapshotSpanCollection spans) {
            ITextSnapshot snapshot = buffer.CurrentSnapshot;
            var snapShot = buffer.CurrentSnapshot;
            StringReader sr = new StringReader(snapShot.GetText());
            var sc = new Scanner(sr);
            var pr = new Parser(sc);
            pr.InitParser(null, snapShot);
            pr.Parse();

            foreach (var span in spans) {
                foreach (var spBlock in pr.SQLBlocks) {
                    yield return new TagSpan<QuerySmartTag>(spBlock, GetSmartTag(spBlock));
                }
            }

            foreach (var span in spans) {
                foreach (var cnBlock in pr.ConnectionBlocks) {
                    yield return new TagSpan<QuerySmartTag>(cnBlock, GetSmartTag2(cnBlock));
                }
            }
        }

        public event EventHandler<SnapshotSpanEventArgs> TagsChanged;

        #endregion

        private QuerySmartTag GetSmartTag(SnapshotSpan snapshotSpan) {
            List<ISmartTagAction> lst = new List<ISmartTagAction>();
            lst.Add(new QueryActionSet(snapshotSpan, this, buffer));
            SmartTagActionSet actionSet = new SmartTagActionSet(new ReadOnlyCollection<ISmartTagAction>(lst));
            List<SmartTagActionSet> lst2 = new List<SmartTagActionSet>();
            lst2.Add(actionSet);
            return new QuerySmartTag(new ReadOnlyCollection<SmartTagActionSet>(lst2));
        }

        private QuerySmartTag GetSmartTag2(SnapshotSpan snapshotSpan) {
            DataExplorerConnectionManager decm = (DataExplorerConnectionManager)provider.ServiceProvider.GetService(typeof(DataExplorerConnectionManager));

            List<ISmartTagAction> lst = new List<ISmartTagAction>();
            foreach (DataExplorerConnection dec in decm) 
                lst.Add(new SelectConnectionActionSet(dec, snapshotSpan, this, buffer));

            lst.Add(new NewConnectionActionSet(snapshotSpan, this, buffer));
            SmartTagActionSet actionSet = new SmartTagActionSet(new ReadOnlyCollection<ISmartTagAction>(lst));
            List<SmartTagActionSet> lst2 = new List<SmartTagActionSet>();
            lst2.Add(actionSet);
            return new QuerySmartTag(new ReadOnlyCollection<SmartTagActionSet>(lst2));
        }

        #region IDisposable Members

        public void Dispose() {
            if (view != null)
                view.LayoutChanged -= new EventHandler<TextViewLayoutChangedEventArgs>(view_LayoutChanged);
            view = null;
            buffer = null;
            provider = null;
        }

        #endregion

        internal class SelectConnectionActionSet : ISmartTagAction
        {
            public SelectConnectionActionSet(DataExplorerConnection dec, SnapshotSpan span, QuerySmartTagger tagger, ITextBuffer buffer) {
                DataConnectionManager dcm = (DataConnectionManager)tagger.provider.ServiceProvider.GetService(typeof(DataConnectionManager));
                DataConnection dc = dcm.GetDataConnection(dec.Provider, dec.EncryptedConnectionString, true);

                this.connectionString = dc.DisplayConnectionString;
                this.displayName = dec.DisplayName;

                this.span = span;
                this.tagger = tagger;
                this.buffer = buffer;
            }

            private SnapshotSpan span;
            private QuerySmartTagger tagger;
            private ITextBuffer buffer;
            private string connectionString;
            private string displayName;

            #region ISmartTagAction Members

            public ReadOnlyCollection<SmartTagActionSet> ActionSets { get { return null; } }
            public string DisplayText { get { return displayName; } }
            public System.Windows.Media.ImageSource Icon { get { return null; } }

            public void Invoke() {
                span.Snapshot.TextBuffer.Replace(span.Span, "\"" + connectionString + "\"");
            }

            public bool IsEnabled { get { return true; } }

            #endregion
        }

        internal class NewConnectionActionSet : ISmartTagAction
        {
            public NewConnectionActionSet(SnapshotSpan span, QuerySmartTagger tagger, ITextBuffer buffer) {
                this.span = span;
                this.tagger = tagger;
                this.buffer = buffer;
            }

            private SnapshotSpan span;
            private QuerySmartTagger tagger;
            private ITextBuffer buffer;

            #region ISmartTagAction Members

            public ReadOnlyCollection<SmartTagActionSet> ActionSets { get { return null; } }
            public string DisplayText { get { return "New Connection"; } }
            public System.Windows.Media.ImageSource Icon { get { return null; } }

            public void Invoke() {
                DataExplorerConnectionManager decm = (DataExplorerConnectionManager)tagger.provider.ServiceProvider.GetService(typeof(DataExplorerConnectionManager));
                DataConnectionManager mdc = (DataConnectionManager)tagger.provider.ServiceProvider.GetService(typeof(DataConnectionManager));

                var dec = decm.PromptAndAddConnection();

                if (dec == null)
                    return;

                DataConnection dc =
                    mdc.GetDataConnection(dec.Provider, dec.EncryptedConnectionString, true);
                span.Snapshot.TextBuffer.Replace(span.Span, "\"" + dc.DisplayConnectionString + "\"");
            }

            public bool IsEnabled { get { return true; } }

            #endregion
        }

        internal class QueryActionSet : ISmartTagAction
        {
            public QueryActionSet(SnapshotSpan span, QuerySmartTagger tagger, ITextBuffer buffer) {
                this.span = span;
                this.tagger = tagger;
                this.buffer = buffer;
            }

            private SnapshotSpan span;
            private QuerySmartTagger tagger;
            private ITextBuffer buffer;

            #region ISmartTagAction Members

            public ReadOnlyCollection<SmartTagActionSet> ActionSets { get { return null; } }
            public string DisplayText { get { return "Transact-SQL Editor"; } }
            public System.Windows.Media.ImageSource Icon { get { return null; } }

            public void Invoke() {
                TSQLEditor.CreateAndShowEditor(tagger.provider, buffer, span);
            }

            public bool IsEnabled { get { return true; } }

            #endregion

        }
    }
}

    
    
